560. 和为 K 的子数组
为保证权益,题目请参考 560. 和为 K 的子数组(From LeetCode).
解决方案1
CPP
C++
/*
* LeetCode 560. 和为K的子数组
*
* Author: Keven Ge
* Date: 2020-05-15
*/
#include <iostream>
#include <cmath>
#include <stack>
#include <unordered_map>
#include <unordered_set>
#include <climits>
#include <vector>
#include <algorithm>
using namespace std;
class Solution {
public:
int subarraySum(vector<int> &nums, int k) {
int ans = 0;
int pra = 0;
unordered_map<int, int> maps;
maps.insert(unordered_map<int, int>::value_type(pra, 1));
// unordered_map<int, int>::iterator it;
for (int num:nums) {
pra += num;
if (maps.find(pra - k) != maps.end()) {
ans += maps[pra-k];
}
if (maps.find(pra) != maps.end()) {
maps[pra]++;
}else{
maps.insert(unordered_map<int, int>::value_type(pra, 1));
}
}
return ans;
}
};
int main() {
vector<int> vec;
vec.push_back(1);
vec.push_back(1);
vec.push_back(1);
vec.push_back(1);
Solution so;
cout << so.subarraySum(vec, 2) << endl;
return 0;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55